<?php

namespace app\common\model\logic;

use app\common\model\dao\AuthApisModel as ApisDao;

class AuthApisModel
{
    public function __construct()
    {
        $this->curModel = new ApisDao();
    }

    public function getRow($data)
    {
        $where[] = ['id', '=', $data['id']];
        $line = $this->getLine($where);
        if ($line->isEmpty()) {
            exception(lang('APIS_NOT'), 0, 'app\\common\\exception\\DataEmptyException');
        } else {
            $line['apis_name'] = $line['module'].'_'.$line['controller'].'_'.$line['action'];

            return $line;
        }
    }

    public function getLine($where)
    {
        return $this->curModel->where($where)->find();
    }

    //保存编辑
    public function saveEdit($data)
    {
        $this->getRow($data);

        return $this->curModel->allowField(true)->isUpdate(true)->save($data);
    }

    //保存添加
    public function saveAdd($data)
    {
        $data['status'] = 1;

        return $this->curModel->allowField(true)->isUpdate(false)->save($data);
    }

    //    清除过期接口
    public function clearExp()
    {
        $apisWhere['update_time'] = ['<', time() - 3600 * 24 * 60]; //超过60天没有人使用的接口 都给清除了
        $apisAll = $this->curModel->where($apisWhere)->all();
        if (!empty($apisAll)) {
            foreach ($apisAll as $ve) {
                $this->saveDel($ve);
            }
        }
    }

    public function run($data)
    {
        $where['code'] = $data['code'];
        $apiRow = $this->getLine($where);
        if (empty($apiRow)) {
            $addData = $data;
            $addData['status'] = 1;
            $this->saveAdd($data);

            return json_encode($where);
        } else {
            $updateData['id'] = $apiRow->id;
            $updateData['status'] = 1;
            $this->saveEdit($updateData);

            return true;
        }
    }

    public function getList()
    {
        $list = $this->curModel->where('id', '>', 0)->all();
        if ($list->isEmpty()) {
            exception(lang('GET_ERROR'), 0, 'app\\common\\exception\\DataEmptyException');
        } else {
            foreach ($list as &$ve) {
                $ve['apis_name'] = $ve['module'].'_'.$ve['controller'].'_'.$ve['action'];
            }

            return $list;
        }
    }
}
